function [k_out] = gen_k_EPU(vec_A, QQ, X_var, X_exp,const_var,data,dates0,lag, Ebar)
% Parameter
NQ = size(QQ,3);
eta = (X_var' - repmat(const_var,size(X_var,1),1)'-[vec_A(1:3*lag)';vec_A(3*lag+1:6*lag)';vec_A(6*lag + 1:9*lag)']*X_exp')';
OMEGA= cov(eta);
BB0=chol(OMEGA,'lower'); %Generate lower cholesy factorization of covariance matrix eta

dates3      = 2011 +  7/12; %2011:07;
dates4      = 2011 +  8/12; %2011:08
dates5      = 1987 + 10/12;
dateslehman = 2008 +  9/12;

%87 crash
index_87 = [find(abs(dates0 - dates5) < 10^(-5))];




% Lehman Crash
index_lehman = [find(abs(dates0 -dateslehman)<10^(-6)):find(abs(dates0 -dateslehman)<10^(-6))];

%ceiling crisis
%index_crsis = [find(dates0 == dates3),find(abs(dates0 -dates4)<10^(-6))];
 index_crsis = [find(dates0 == dates3)];


e_store = NaN(NQ,4);
for iii = 1:NQ
    
    % rotate and normalize B
    B_initial=BB0*QQ(:,:,iii);
    B_est=B_initial*diag(sign(diag(B_initial))); %normalize so that self-irfs are positive
    ehat = eta(:,:)*inv(B_est)';
    
    %============ Event constraint ==============
    %      Ebar(1)               Ebar(2)          Ebar(3)
    kkk = [ehat(index_lehman,3)  ehat(index_87,3) ehat(index_crsis,1)' ehat(index_crsis,3)'];
    
   %B_store(:,:,iii) = B_est;
    e_store(iii,:) = kkk;   
end


k_out = prctile(e_store,75);
end